<template>
  <el-table
    v-loading="loading ?? false"
    :data="tableData"
    :stripe="true"
    :show-overflow-tooltip="true"
    highlight-current-row
    @current-change="handleCurrentChange"
    @filter-change="handleFilterChange"
    :span-method="mergeFields && mergeFields.length ? tableSpanMethod : undefined"
  >
  <template
    v-for="column in columns"
    :key="column.prop">
    <el-table-column v-if="column.type === 'selection'" :label="column.label" :width="column.width" :align="column.align || 'center'">
      <template #header>
        <el-checkbox 
          v-model="selectAll" 
          :indeterminate="isIndeterminate"
          @change="handleSelectAllChange"
        />
      </template>
      <template #default="scope">
        <el-checkbox 
          v-model="scope.row.selected" 
          @change="handleRowSelectionChange(scope.row)"
        />
      </template>
    </el-table-column>
  
    <el-table-column v-else
      :label="column.label"
      :prop="column.prop"
      :align="column.align || 'center'"
      :formatter="column.formatter"
      :width="column.width"
      :fixed="column.fixed"
      v-bind="getColumnProps(column)"
    >
      <template #default="scope">
        <!-- 禁用状态下的显示 -->
        <template v-if="isDisabled">
          <el-checkbox-group v-model="scope.row[column.prop]" v-if="column.type==='checkbox'" style="margin: auto">
            <el-checkbox />
          </el-checkbox-group>
          <!-- 操作列按钮组 -->
          <template v-else-if="column.buttons && Array.isArray(column.buttons)">
            <el-button
              v-for="btn in column.buttons"
              :key="btn.key || btn.text"
              :link="btn.link || false"
              :type="(['', 'default', 'text', 'success', 'warning', 'info', 'primary', 'danger'].includes(btn.type as string) ? btn.type : 'text')"
              :size="btn.size || 'small'"
              :disabled="btn.disabled"
              @click="$emit('button-click', { action: btn.action, row: scope.row })"
            >
              <Icon v-if="btn.icon" :icon="btn.icon" class="mr-5px" />
              {{ btn.text || scope.row[column.prop] }}
            </el-button>
          </template>
          <!-- 其他列渲染 -->
          <template v-else-if="column.slot">
            <slot :name="column.slot" :row="scope.row" :scope="scope" ></slot>
          </template>
          <template v-else-if="column.type === 'date'">
            <span
              :class="column.className"
              @click="column.on?.click && column.on.click(scope.row, scope)"
              @dblclick="column.on?.dblclick && column.on.dblclick(scope.row, scope)"
            >
              {{ dateFormatter(scope.row, column.prop as any, scope.row[column.prop]) }}
            </span>
          </template>
          <template v-else >
            <el-input v-model="scope.row[column.prop]" disabled />
          </template>
        </template>
        
        <!-- 可编辑状态下的显示 -->
        <template v-else>
          <!-- Checkbox类型 -->
          <el-checkbox-group 
            v-if="column.type==='checkbox'" 
            v-model="scope.row[column.prop]" 
            style="margin: auto"
          >
            <el-checkbox />
          </el-checkbox-group>
          
          <!-- 日期类型 -->
          <el-date-picker
            v-else-if="column.type === 'date'"
            v-model="scope.row[column.prop]"
            :type="(column.dateType as any) || 'date'"
            :value-format="column.valueFormat || 'YYYY-MM-DD'"
            :format="column.format || 'YYYY-MM-DD'"
            :placeholder="column.placeholder || '请选择日期'"
            style="width: 100%"
            class="text-center"
          />
          
          <!-- 选择类型 -->
          <el-select
            v-else-if="column.type === 'select'"
            v-model="scope.row[column.prop]"
            :placeholder="column.placeholder || '请选择'"
            :clearable="column.clearable !== false"
            :filterable="column.filterable !== false"
            style="width: 100%"
          >
            <el-option
              v-for="option in column.options || []"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          
          <!-- 文本域类型 -->
          <el-input
            v-else-if="column.type === 'textarea'"
            v-model="scope.row[column.prop]"
            type="textarea"
            :rows="column.rows || 1"
            :placeholder="column.placeholder || '请输入'"
            class="text-center"
          />
          
          <!-- 数字类型 -->
          <el-input-number
            v-else-if="column.type === 'number'"
            v-model="scope.row[column.prop]"
            :min="column.min"
            :max="column.max"
            :precision="column.precision"
            :step="column.step || 1"
            :placeholder="column.placeholder || '请输入数字'"
            style="width: 100%"
          />
          
          <!-- 操作列按钮组 -->
          <template v-else-if="column.buttons && Array.isArray(column.buttons)">
            <el-button
              v-for="btn in column.buttons"
              :key="btn.key || btn.text"
              :link="btn.link || false"
              :type="(['', 'default', 'text', 'success', 'warning', 'info', 'primary', 'danger'].includes(btn.type as string) ? btn.type : 'text')"
              :size="btn.size || 'small'"
              :disabled="btn.disabled"
              @click="$emit('button-click', { action: btn.action, row: scope.row })"
            >
              <Icon v-if="btn.icon" :icon="btn.icon" class="mr-5px" />
              {{ btn.text || scope.row[column.prop] }}
            </el-button>
          </template>
          
          <!-- 自定义slot -->
          <template v-else-if="column.slot">
            <slot :name="column.slot" :row="scope.row" :scope="scope" ></slot>
          </template>
          
          <!-- 默认文本输入 -->
          <el-input
            v-else
            v-model="scope.row[column.prop]"
            :placeholder="column.placeholder || '请输入'"
          />
        </template>
      </template>
    </el-table-column>
    </template>
  </el-table>
</template>

<script setup lang="ts">
import { defineEmits, defineProps, computed, watch } from 'vue';
import { dateFormatter } from '@/utils/formatTime'
import type { TableColumnCtx } from 'element-plus'

const emit = defineEmits(['current-change', 'select-change', 'button-click', 'filter-change']);

interface TableColumn {
  fixed?: 'left' | 'right' | boolean;
  prop: string;
  label: string;
  align?: string;
  formatter?: (row: any, column: any, cellValue: any, index: number) => string;
  width?: string | number;
  buttons?: Array<any>;
  slot?: string;
  className?: string;
  type?: string; // 支持'date', 'checkbox', 'select', 'textarea', 'number'
  placeholder?: string;
  clearable?: boolean;
  filterable?: boolean;
  options?: Array<{ label: string; value: any }>;
  rows?: number;
  min?: number;
  max?: number;
  precision?: number;
  step?: number;
  dateType?: string;
  valueFormat?: string;
  format?: string;
  on?: {
    click?: (row: any, scope: any) => void;
    dblclick?: (row: any, scope: any) => void;
  };
}

const props = defineProps<{
  isDisabled?: boolean;
  columns: TableColumn[];
  tableData: any[];
  loading?: boolean;
  mergeFields?: string[]; // 新增：需要合并的字段名数组
}>();

// 全选相关的计算属性
const selectAll = computed({
  get: () => {
    return props.tableData.length > 0 && props.tableData.every(row => row.selected)
  },
  set: (value: boolean) => {
    // 这个setter会在handleSelectAllChange中处理
  }
})

const isIndeterminate = computed(() => {
  const selectedCount = props.tableData.filter(row => row.selected).length
  return selectedCount > 0 && selectedCount < props.tableData.length
})

// 全选/取消全选处理函数
const handleSelectAllChange = (value: boolean) => {
  props.tableData.forEach(row => {
    row.selected = value
    emit('select-change', row)
  })
}

const handleCurrentChange = (row: any) => {
  emit('current-change', row);
};

const handleSelectionChange = (row: any) => {
  emit('select-change', row)
}

const handleRowSelectionChange = (row: any) => {
  // 确保selected属性存在
  if (row.selected === undefined) {
    row.selected = false
  }
  emit('select-change', row)
}


const getColumnProps = (row: any) => {
  // console.log(row)
  if(row.filters) {
    return {
      filters: row.filters,
      'filter-method': filterHandler
    }
  }
  return {}
}

const filterHandler = (
  value: string,
  row: any,
  column: TableColumnCtx<any>
) => {
  const property = column['property']
  return row[property] === value
}

const handleFilterChange = (row: any) => {
  emit('filter-change', row)
}

// 合并单元格方法
function tableSpanMethod({ row, column, rowIndex, columnIndex }: any) {
  // debugger
  if (!props.mergeFields?.length) return [1, 1];
  const prop = column.property;
  if (!props.mergeFields.includes(prop)) return [1, 1];

  const data = props.tableData;
  let rowspan = 1;
  let colspan = 1;

  // 只处理纵向合并
  if (
    rowIndex === 0 ||
    data[rowIndex][prop] !== data[rowIndex - 1][prop]
  ) {
    for (let i = rowIndex + 1; i < data.length; i++) {
      if (data[i][prop] === row[prop]) {
        rowspan++;
      } else {
        break;
      }
    }
    return [rowspan, colspan];
  } else {
    return [0, 0];
  }
}
</script>